<template>
  <div class="login-body">
    <div class="bg">
      <img src="../../assets/login_img.png" />
    </div>
    <div class="login-panel">
      <h3 class="logo">皓明云盘</h3>
      <el-form
        class="login-register"
        :model="formData"
        :rules="rules"
        ref="formDataRef"
      >
        <!-- 邮箱 -->
        <el-form-item prop="email">
          <el-input
            size="large"
            clearable
            placeholder="请输入邮箱"
            v-model.trim="formData.email"
            maxLength="150"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>
        <!--登录密码-->
        <el-form-item prop="password" v-if="opType == 1">
          <el-input
            type="password"
            size="large"
            placeholder="请输入密码"
            v-model.trim="formData.password"
            show-password
            ><template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>

        <!--注册-->
        <div v-if="opType == 0 || opType == 2">
          <!-- 邮箱验证码 -->
          <el-form-item prop="emailCode">
            <div class="send-email-panel">
              <el-input
                clearable
                size="large"
                placeholder="请输入邮箱验证码"
                v-model="formData.emailCode"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span> </template
              ></el-input>
              <el-button
                class="send-mail-btn"
                type="primary"
                plain
                size="large"
                @click="getEmailCode"
                ><span>发送验证码</span></el-button
              >
            </div>
          </el-form-item>
          <!--昵称-->
          <el-form-item prop="nickName" v-if="opType == 0">
            <el-input
              clearable
              size="large"
              placeholder="请输入昵称"
              v-model.trim="formData.nickName"
              maxLength="20"
              ><template #prefix>
                <span class="iconfont icon-account"></span> </template
            ></el-input>
          </el-form-item>

          <!--注册密码 -->
          <el-form-item prop="registerPassword">
            <el-input
              clearable
              type="password"
              size="large"
              placeholder="请输入密码"
              show-password
              v-model.trim="formData.registerPassword"
              ><template #prefix>
                <span class="iconfont icon-password"></span> </template
            ></el-input>
          </el-form-item>
          <!-- 重复密码 -->
          <el-form-item prop="reRegisterPassword">
            <el-input
              clearable
              type="password"
              size="large"
              placeholder="请再次输入密码"
              show-password
              v-model.trim="formData.reRegisterPassword"
              ><template #prefix>
                <span class="iconfont icon-password"></span> </template
            ></el-input>
          </el-form-item>
        </div>

        <!--验证码-->
        <el-form-item prop="checkCode">
          <div class="check-code-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formData.checkCode"
              @keyup.enter="doSubmit"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrl"
              class="check-code"
              @click="changeCheckCode(0)"
            />
          </div>
        </el-form-item>
        <!--找回密码 注册 转换按钮 -->
        <el-form-item v-if="opType == 1">
          <div class="rememberme-panel">
            <el-checkbox v-model="formData.rememberme">记住我</el-checkbox>
          </div>
          <div class="no-account">
            <a href="javascript:void(0)" class="a-link" @click="showPanel(2)"
              >忘记密码？</a
            >
            <a href="javascript:void(0)" class="a-link" @click="showPanel(0)"
              >没有账号？</a
            >
          </div>
        </el-form-item>
        <!-- 返回登录-->
        <el-form-item v-if="opType == 2 || opType == 0">
          <a href="javascript:void(0)" class="a-link" @click="showPanel(1)"
            >去登陆？</a
          >
        </el-form-item>
        <!--登录按钮-->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="op-btn"
            @click="doSubmit"
          >
            <span v-if="opType == 2">重置密码</span>
            <span v-if="opType == 1">登录</span>
            <span v-if="opType == 0">注册</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <Dialog
      :show="dialogConfig4SendMailCode.show"
      :title="dialogConfig4SendMailCode.title"
      :buttons="dialogConfig4SendMailCode.buttons"
      width="400px"
      :showCancel="false"
      @close="dialogConfig4SendMailCode.show = false"
    >
      <el-form
        :model="formData4SendMailCode"
        :rules="rules"
        ref="formData4SendMailCodeRef"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="邮箱:">
          {{ formData.email }}
        </el-form-item>
        <el-form-item label="验证码:" prop="checkCode">
          <div class="check-code-panel">
            <el-input
              size="large"
              placeholder="请输入验证码"
              v-model.trim="formData4SendMailCode.checkCode"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img
              :src="checkCodeUrl4SendMailCode"
              class="check-code"
              @click="changeCheckCode(1)"
            />
          </div>
        </el-form-item>
      </el-form>
      <!--验证码-->
    </Dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import md5 from "js-md5";
import { SendEmailCode, Register, Login, ResetPwd } from "@/api/account";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const api = {
  // 验证码
  checkCode: "/api/checkCode",
};

// 操作类型 0：注册 1：登录 2：重置密码
const opType = ref(1);
const showPanel = (type) => {
  opType.value = type;
  resetForm();
};
onMounted(()=>{
  resetForm(1);
})
// 检查密码是否一致
const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.registerPassword) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};

const formData = ref({});
const formDataRef = ref();
const rules = {
  email: [
    { required: true, message: "请输入邮箱" },
    { validator: proxy.Verify.email, message: "请输入正确的邮箱" },
  ],
  password: [{ required: true, message: "请输入密码" }],
  emailCode: [{ required: true, message: "请输入邮箱验证码" }],
  nickName: [{ required: true, message: "请输入昵称" }],
  registerPassword: [
    { required: true, message: "请输入密码" },
    {
      validator: proxy.Verify.password,
      message: "密码只能是数字、字母、特殊字符，8-18位",
    },
  ],
  reRegisterPassword: [
    { required: true, message: "请输入确认密码" },
    { validator: checkRePassword, message: "两次密码输入不一致" },
  ],
  checkCode: [{ required: true, message: "请输入图片验证码" }],
};

const checkCodeUrl = ref(api.checkCode);
const checkCodeUrl4SendMailCode = ref(api.checkCode);
// 重新获取验证码方法
const changeCheckCode = (type) => {
  if (type == 0) {
    checkCodeUrl.value =
      api.checkCode + "?type=" + type + "&time=" + new Date().getTime();
  } else {
    checkCodeUrl4SendMailCode.value =
      api.checkCode + "?type=" + type + "&time=" + new Date().getTime();
  }
};

// 发送邮箱验证码
const formData4SendMailCode = ref({});
const formData4SendMailCodeRef = ref();

const dialogConfig4SendMailCode = reactive({
  show: false,
  title: "发送邮箱验证码",
  buttons: [
    {
      type: "primary",
      text: "发送验证码",
      click: (e) => {
        sendEmailCode();
      },
    },
  ],
});

// 发送邮箱验证码
const sendEmailCode = () => {
  formData4SendMailCodeRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const params = Object.assign({}, formData4SendMailCode.value);
    params.type = opType.value == 0 ? 0 : 1;
    const res = await SendEmailCode(params, () => {
      changeCheckCode(1);
    });
    if (!res) {
      return;
    }
    proxy.Message.success("验证码发送成功，请前往邮箱查看");
    dialogConfig4SendMailCode.show = false;
  });
};

const getEmailCode = () => {
  // 校验表单
  formDataRef.value.validateField("email", (valid) => {
    if (!valid) {
      return;
    }
    dialogConfig4SendMailCode.show = true;
    // 打开弹框要清空数据
    nextTick(() => {
      changeCheckCode(1);
      formData4SendMailCodeRef.value.resetFields();
      formData4SendMailCode.value = {
        email: formData.value.email,
      };
    });
  });
};
// 提交表单（登录注册重置密码）
const doSubmit = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    let params = {};
    Object.assign(params, formData.value);
    let res = null;
    switch (opType.value) {
      // 注册
      case 0:
        params.password = params.registerPassword;
        delete params.registerPassword;
        delete params.reRegisterPassword;
        res = await Register(params, () => {
          changeCheckCode(0);
        });
        if (!res) {
          return;
        }
        proxy.Message.success("注册成功，请登录");
        showPanel(1);
        break;
      // 登录
      case 1:
        // 判断cookie是否有保存密码
        let cookieLoginInfo = proxy.VueCookies.get("loginInfo");
        let cookiePassword =
          cookieLoginInfo == null ? null : cookieLoginInfo.password;
        // 如果输入的密码与保存的密码不同
        if (params.password !== cookiePassword) {
          params.password = md5(params.password);
        }
        res = await Login(params, () => {
          changeCheckCode(0);
        });
        if (!res) {
          return;
        }
        // 登录没选择记住我 就移除cookies
        if (!params.rememberme) {
          proxy.VueCookies.remove("loginInfo");
        }
        const loginInfo = {
          email: params.email,
          password: params.password,
          rememberme: params.rememberme,
        };
        proxy.VueCookies.set("loginInfo", loginInfo, "7d");
        proxy.Message.success("登录成功");
        // 存储用户信息cookie
        proxy.VueCookies.set("userInfo", res.data, 0);
        // 重定向到原始页面
        const redirectUrl = route.query.redirectUrl || "/";
        router.push(redirectUrl);
        break;
      // 重置密码
      case 2:
        params.password = params.registerPassword;
        delete params.registerPassword;
        delete params.reRegisterPassword;
        res = await ResetPwd(params, () => {
          changeCheckCode(0);
        });
        if (!res) {
          return;
        }
        proxy.Message.success("重置密码成功，请登录");
        showPanel(1);
        break;
    }
  });
};
// 重置表单信息
const resetForm = () => {
  changeCheckCode(0);
  formDataRef.value.resetFields();
  formData.value = {};
  if (opType.value == 1) {
    // 要从cookie拿用户的登录密码和账号
    const cookieLoginInfo = proxy.VueCookies.get("loginInfo");
    if (cookieLoginInfo) {
      formData.value = cookieLoginInfo;
    }
  }
};
</script>

<style lang="scss" scoped>
.login-body {
  background-size: cover;
  background-color: var(--theme);
  display: flex;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  min-width: 375px;
  justify-content: space-around;
  flex-direction: row;
  align-items: center;
  @media (max-width: 968px) {
    justify-content: space-around;
    flex-direction: column;
    align-items: center;
    .bg {
      padding-top: 139px;
      padding-bottom: 139px;
      img {
        width: 99.73333333vw;
        height: 62.816vw;
      }
      order: 2;
    }
    .login-panel {
      margin-top: 139px;
      order: 1;
    }
  }
  .bg {
    display: flex;
    align-items: center;

    img {
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
      border-radius: 20px;
      width: 56.5625vw;
      height: 35.625vw;
    }
  }
  .login-panel {
    width: 390px;
    min-height: 600px;

    .logo {
      font-size: 35px;
      font-weight: 600;
      text-align: center;
    }
    .login-register {
      transition: all 1s;
      padding: 25px;
      background: #fff;
      border-radius: 20px;
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
      .send-email-panel {
        display: flex;
        width: 100%;
        justify-content: space-between;
        .send-mail-btn {
          margin-left: 5px;
        }
      }

      .rememberme-panel {
        width: 100%;
      }
      .no-account {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .check-code-panel {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
    .check-code {
      margin-left: 5px;
      cursor: pointer;
    }
  }
}
</style>>
